﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.InvoiceManagements;
using Reporting.Domain;
using Reporting.Errorcode;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.InvoiceManagements;

namespace Reporting.API.Application.CommandHandler.InvoiceManagements
{
    /// <summary>
    /// 删除  开票
    /// </summary>
    public class DeleteInvoiceManagementCommandHandler : IRequestHandler<DeleteInvoiceManagementCommand, ApiResult>
    {
        private readonly IInvoiceManagementRepository _invoiceManagementRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<DeleteInvoiceManagementCommandHandler> _logger;

        public DeleteInvoiceManagementCommandHandler(ILogger<DeleteInvoiceManagementCommandHandler> logger, IMapper mapper, IInvoiceManagementRepository invoiceManagementRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _invoiceManagementRepository = invoiceManagementRepository;
        }

        public async Task<ApiResult> Handle(DeleteInvoiceManagementCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // id查询生产工单
                var InvoiceManagements = await _invoiceManagementRepository.GetAsync(x => x.Invoicemanagementid == request.Invoicemanagementid);
                if (InvoiceManagements == null)
                {
                    return ApiResult.Fail("删除失败，当前数据不存在", StatusCodeEnum.BadRequest);
                }
                // 删除生产工单
                var result = await _invoiceManagementRepository.DeleteAsync(InvoiceManagements);
                return ApiResult.Success(StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生产工单删除失败");
                throw;
            }
        }
    }
}
